package com.clouddisk.file.decorator.impl;

import com.clouddisk.file.decorator.FileHandlerDecorator;
import com.clouddisk.file.strategy.FileHandler;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

/**
 * 文件压缩装饰器
 */
public class CompressionDecorator extends FileHandlerDecorator {

    public CompressionDecorator(FileHandler fileHandler) {
        super(fileHandler);
    }

    @Override
    public String handleUpload(MultipartFile file) {
        // 在上传前压缩文件
        try {
            byte[] compressed = compress(file.getBytes());
            // TODO: 将压缩后的文件上传
            return super.handleUpload(file);
        } catch (IOException e) {
            throw new RuntimeException("文件压缩失败", e);
        }
    }

    @Override
    public byte[] handlePreview(String storagePath) {
        // 获取文件内容并解压
        byte[] compressed = super.handlePreview(storagePath);
        // TODO: 解压文件
        return compressed;
    }

    private byte[] compress(byte[] data) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream)) {
            gzipOutputStream.write(data);
        }
        return outputStream.toByteArray();
    }
} 